import { EHttpStatus } from "@/enums/httpCode.enum.ts";
import { Message } from "@/models/message.model.ts";
import { EMessageType } from "@/enums/messageType.enum.ts";
import { IUser, User } from "@/users/user.ts";

const room = new Map<string, IUser>();

Deno.serve((req, _info) => {
  if (req.headers.get('upgrade') !== "websocket") {
    return new Response(null, {
      // 未实现（Not Implemented）
      status: EHttpStatus.NotImplemented
    });
  }

  const { socket, response } = Deno.upgradeWebSocket(req, {});
  socket.addEventListener("open", function (_evt) {
    socket.send(new Message({
      type: EMessageType.SYSTEM,
      username: "system",
      content: "服务器open了",
    }).toJsonString());
  });
  socket.addEventListener("message", function (evt) {
    const msg = Message.toJsonObj(evt.data);
    console.log("message:", msg);
    const msgType = msg.type as EMessageType;
    switch (msgType) {
      case EMessageType.TEXT:
        room.forEach(p => p.socket.send(new Message({
          type: EMessageType.TEXT,
          username: msg.username,
          content: msg.content,
        }).toJsonString()));
        break;
      case EMessageType.SYSTEM:
        if (!room.has(msg.username)) {
          room.set(msg.username, new User({
            username: msg.username,
            socket: socket
          }));
        }
        room.forEach(p => p.socket.send(new Message({
          type: msg.type,
          username: msg.username,
          content: "服务器已连接。"
        }).toJsonString()));
        break;
    }
  });
  socket.addEventListener("close", function (_evt) {
  });
  socket.addEventListener("error", function (_evt) {
  });

  return response;
});
